// pages/play/play.js
//let rotate = 0; //旋转角度默认为为0
var app = getApp(); 
var util = require("../../utils/util.js")
var varName;
var that;
var ctx = wx.createCanvasContext('canvasArcCir');
var playModels = {
  singleModel: 1,
  listModel: 2,
  randomModel: 3,
};
const bgAudioManager = wx.getBackgroundAudioManager()
Page({
  data: {
    picUrl: "",
    musicUrl: "",
    author: "",
    name: "",
    songname:"",
    isplaying:false,
    duration_minute: "",
    duration_seconds:"",
    currTime_minute: "",
    currTime_seconds:"",
    playpicpath: "../../pause.png",
    modepath:"../../sx.png",
    songslist:[],
    songindex:0,
    myModel: playModels.listModel,

    lastTouchedX:0,
    lastTouchedY:0,
    currentGesture: 0,

    startAngle: 1.5 * Math.PI,
    endAngle:0,
    text:"",

    infopage:"",
    lyricpage:"none",
    lyric:null,
    scrollTop:0,
    lyricSwiperH:300,
    errormsg: "暂无歌词~",
  },
  onLoad: function () {
    that = this;
    this.data.songslist = app.globalData.playSongList

    bgAudioManager.onPlay(function () {
      that.data.playpicpath= "../../pause.png"
      console.log(bgAudioManager.duration)
    });
    bgAudioManager.onPause(function () {
      that.data.playpicpath = "../../play.png"
    })
    bgAudioManager.onEnded(function () {
      // console.log('onBackgroundAudioEnded')
      if (that.data.myModel == playModels.singleModel) {
        that.playMusic();
      }
      else if (that.data.myModel == playModels.listModel || that.data.myModel == playModels.randomModel) {
        that.data.isplaying = true;
        that.nextMusic()

      }      
    })
    bgAudioManager.onTimeUpdate(function (){
      that.data.endAngle = bgAudioManager.currentTime * 2 * Math.PI / bgAudioManager.duration + 1.5 * Math.PI;
      var dm = Math.floor(bgAudioManager.duration / 60)
      var ds = Math.floor(bgAudioManager.duration) % 60
      var cm = Math.floor(bgAudioManager.currentTime / 60)
      var cs = Math.floor(bgAudioManager.currentTime) % 60
      // console.log(cs)
      that.setData({
        duration_minute: (dm >= 10 ? dm.toString() : "0" + dm.toString()),
        duration_seconds: (ds >= 10 ? ds.toString() : "0" + ds.toString()),
        currTime_minute: (cm >= 10 ? cm.toString() : "0" + cm.toString()),
        currTime_seconds: (cs >= 10 ? cs.toString() : "0" + cs.toString()),

      })

      // console.log(that.data.currTime_minute)
      // console.log(that.data.currTime_seconds)
      that.drawArc(that.data.startAngle, that.data.endAngle);
    })
  },
  onReady: function () {
    console.log("onReady")
    that=this;
    this.data.songindex = app.globalData.playSong
    console.log(this.data.songslist[this.data.songindex])
    var currplaysongJson = this.data.songslist[this.data.songindex]
    this.setData({
      picUrl: "http://y.gtimg.cn/music/photo_new/T002R150x150M000" + currplaysongJson.albummid + '.jpg',
      name: currplaysongJson.songname,
      songname: currplaysongJson.songname,
      musicUrl: 'http://ws.stream.qqmusic.qq.com/C100' + currplaysongJson.songmid + '.m4a?fromtag=38',
      author: currplaysongJson.singer[0].name
    });
    this.playMusic();

    //this.audioCtx = wx.createAudioContext("myAudio");
    var circles = new Array("c0", "c1", "c2");
    for(var i = 0;i < 3; i++){
      //创建并返回绘图上下文context对象。
      var cxt_arc = wx.createCanvasContext(circles[i]);
      cxt_arc.setLineWidth(6);
      cxt_arc.setStrokeStyle('#eaeaea');
      cxt_arc.setLineCap('round');
      cxt_arc.beginPath();
      if(i == 1){
        cxt_arc.arc(55, 50, 45, 0, 2 * Math.PI, false);
      }
      else{
        cxt_arc.arc(55, 50, 35, 0, 2 * Math.PI, false);
      }
      
      cxt_arc.stroke();
      cxt_arc.draw();
    }
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          lyricSwiperH: res.windowHeight - 210
        })
      }
    });
    this.loadlyric(currplaysongJson);
  },
  onShow(){
    console.log("Onshow")

  },
  onHide(){
    console.log("OnHide")
  },
  loadlyric: function ( currplaysongJson) {
    var songlist = this.data.songslist;
    var index = this.data.songindex;
    var id = currplaysongJson.songid;
    var mid = currplaysongJson.songmid;
    var albummid = currplaysongJson.albummid;
    //console.log(currplaysongJson.songid)
    // 修改配置
    this.changeOption(index, id, mid, albummid, songlist);
  },
  // 修改配置
  changeOption:function(index, id, mid, albummid, songlist){
    this.getLyric(id)
  },

  // 获取歌词
  getLyric:function(id){
    that = this;
    util.getLyric(id, function (data){
      if (data.showapi_res_body.lyric){
        var lyric = that.reconvert(data.showapi_res_body.lyric).slice(4);
        lyric = that.parseLyric(lyric)
        that.setData({
          lyric: lyric
        });
      }
    });
  },

  // 解码>中文
  reconvert:function(str){
    str = str.replace(/(\\u)(\w{1,4})/gi, function ($0) {
      return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
    });
    str = str.replace(/(&#x)(\w{1,4});/gi, function ($0) {
      return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16));
    });
    str = str.replace(/(&#)(\d{1,6});/gi, function ($0) {
      return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
    });
    return str;
  },

  // 解析歌词
  parseLyric:function(lrc){
    var lyrics = lrc.split("\n");
    var lrcObj = {};
    for (var i = 0; i < lyrics.length; i++) {
      var lyric = decodeURIComponent(lyrics[i]);
      var timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
      var timeRegExpArr = lyric.match(timeReg);
      if (!timeRegExpArr)
        continue;
      var clause = lyric.replace(timeReg, '');
      if (clause.length > 0) {
        for (var k = 0, h = timeRegExpArr.length; k < h; k++) {
          var t = timeRegExpArr[k];
          var min = Number(String(t.match(/\[\d*/i)).slice(1)),
            sec = Number(String(t.match(/\:\d*/i)).slice(1));
          var time = min * 60 + sec;
          lrcObj[time] = clause;
        }
      }
    }
    return lrcObj;
  },
  onHind: function () {
    console.log("onHind")
  },
  handletouchtart: function (event) {
    this.setData({
      lastTouchedX : event.touches[0].pageX,
      lastTouchedY : event.touches[0].pageY,
      text:"开始触摸"
    })
  },
  handletouchmove: function (event) {
    let currentX = event.touches[0].pageX
    let currentY = event.touches[0].pageY
    let tx = currentX - this.data.lastTouchedX
    let ty = currentY - this.data.lastTouchedY
    let text = "";
    //左右方向滑动
    if (Math.abs(tx) > 0) {
      if (tx < 0) {
        text = "向左滑动";
       // this.data.currentGesture=1;
        
      }
      else if (tx > 0) {
        text = "向右滑动";
        //this.data.currentGesture=2;
      }
      var tempAngle = this.data.endAngle +tx*2 * Math.PI / bgAudioManager.duration;
      console.log("tempangle:" + tempAngle / Math.PI+'PI')
      this.drawArc(this.data.startAngle, tempAngle);
      this.data.endAngle=tempAngle;
      console.log("handletouchmove此时进度:" + bgAudioManager.duration *(this.data.endAngle - 1.5 * Math.PI) / (2 * Math.PI))
    }
    //将当前坐标进行保存以进行下一次计算
    this.data.lastTouchedX = currentX
    this.data.lastTouchedY = currentY
  },
  handletouchend: function (event) {
    this.setData({
      //currentGesture:0,
      text: "停止滑动",
    });
    bgAudioManager.seek(bgAudioManager.duration * (this.data.endAngle - 1.5 * Math.PI) / (2 * Math.PI));
    //console.log("endAngle end：" + this.data.endAngle)
  },
  // 改变播放模式 顺序、单曲、随机
  changeplaymode: function(){
    if (this.data.myModel == playModels.singleModel){
      this.setData({
        myModel: playModels.listModel,
        modepath:"../../sx.png"
      });
      
    }
    else if (this.data.myModel == playModels.listModel){
      this.setData({
        myModel: playModels.randomModel,
        modepath: "../../random.png"
      });
    }
    else{
      this.setData({
        myModel: playModels.singleModel,
        modepath: "../../danqu.png"
      });
    }
  },
  // 开始音乐-
  playMusic: function (e) {
    this.setData({
      isplaying:true,
    });
    bgAudioManager.src = this.data.musicUrl;
    bgAudioManager.play()

  },
  // 暂停音乐
  pauseMusic: function () {
    this.setData({
      isplaying:false
    });
    bgAudioManager.pause()
  },
  // 点击播放按钮，切换播放暂停图片
  switchPic: function () {
    if (this.data.isplaying) {
      this.pauseMusic()
      this.setData({
        playpicpath: "../../play.png"
      });
    }
    else {
      this.playMusic()
      this.setData({
        playpicpath: "../../pause.png"
      });
    }
  },
  //下一首歌曲
  nextMusic:function(){
    var add_index=0
    if (this.data.myModel == playModels.listModel || this.data.myModel == playModels.singleModel)
      add_index=1;
    else if (this.data.myModel == playModels.randomModel)
      add_index = Math.floor(Math.random() * app.globalData.songnum);
    //console.log(this.data.myModel)
    this.setData({
      songindex: (this.data.songindex + add_index) % app.globalData.songnum
    })
    var currplaysongJson = this.data.songslist[this.data.songindex];
    this.setData({
      isplaying:this.data.isplaying,
      picUrl: "http://y.gtimg.cn/music/photo_new/T002R150x150M000" + currplaysongJson.albummid + '.jpg',
      name: currplaysongJson.songname,
      songname: currplaysongJson.songname,
      musicUrl: 'http://ws.stream.qqmusic.qq.com/C100' + currplaysongJson.songmid + '.m4a?fromtag=38',
      author: currplaysongJson.singer[0].name
    });
    //console.log("isplaying:"+this.data.isplaying);
    this.loadlyric(currplaysongJson);
    if (this.data.isplaying)
      this.playMusic();
    else{
      ctx.clearRect(0, 0, 110, 100);
      ctx.draw()
    }
  },

  playEnd:function(){
    if (this.data.myModel == playModels.singleModel){
      this.playMusic();
    }

    else if (this.data.myModel == playModels.listModel || this.data.myModel == playModels.randomModel){
      this.data.isplaying=true;
      this.nextMusic()

    }
  },

  drawArc: function(s, e) {
    ctx.setFillStyle('white');
    ctx.clearRect(0, 0, 40, 40);
    ctx.draw();
    var x = 55, y = 50, radius = 45;
    ctx.setLineWidth(7);
    ctx.setStrokeStyle('#facb38');
    ctx.setLineCap('round');
    ctx.beginPath();
    ctx.arc(x, y, radius, s, e, false);
    ctx.stroke()
      ctx.draw()
  },
  // 点击歌曲封面切换至歌词
  showlyric:function(){
    this.setData({
      infopage:"none",
      lyricpage:""
    })
  },
  // 点击歌词切换至歌曲封面
  showsonginfo:function(){
    this.setData({
      infopage:"",
      lyricpage:"none"
    })
  },
})